/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Vocabulary;

import org.myontology.users.Login;
import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.repository.RepositoryConnection;

import controller.HelperFunctions;
import controller.elementMapper.ClassMapper;
import controller.elementMapper.Mapper;
import controller.sesameDataConnector.AbstractDataConnector;

/**
 * Servlet implementation class for Servlet: Update
 *
 */
public class UpdateHierarchyByDND extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	 static final long serialVersionUID = 6L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public UpdateHierarchyByDND() {
		super();
	}   	

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		
		if ( !Login.LOGGED_IN.getValue(request) ) {			
			response.sendRedirect( request.getContextPath() + "/login");
			return;
		}
		
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		
		String ret_ok="";
		String ret_par="";
		
		try{
		String concept = controller.HelperFunctions.getEncodedURI(request.getParameter( "concept" ).trim());
		String newParent = controller.HelperFunctions.getEncodedURI(request.getParameter( "nP" ).trim());
		String oldParent = controller.HelperFunctions.getEncodedURI(request.getParameter( "oP" ).trim());
		
		URI uri_concept = null;
		URI uri_nParent = null;
		URI uri_oParent = null;
		

		RepositoryConnection con = null;
		
				uri_concept = new URIImpl(Vocabulary.NAMESPACE.stringValue()+concept );
				uri_nParent = new URIImpl(Vocabulary.NAMESPACE.stringValue()+newParent );
				uri_oParent = new URIImpl(Vocabulary.NAMESPACE.stringValue()+oldParent );
				
				if (uri_nParent.equals(uri_concept))
					// no recursion is allowed (child may not be its own parent)
					// this error may never occur, as already catched on the client !
					ret_ok = "\"err0\"";
				else if (HelperFunctions.isSubclassOf(uri_concept, uri_nParent)){
					// is already assigned to new super-node
					// this error may never occur, as D&D is only possible for already loaded nodes
					// theoretically possible due to collaborative working
					ret_ok = "\"err1\"";
				}else if (!uri_oParent.getLocalName().equals("") && !HelperFunctions.isSubclassOf(uri_concept, uri_oParent)){
					// means that class is not subclass of old super-node
					// normally not possible,...
					// only thinkable in the case another user changed the structure in the meantime
					ret_ok = "\"err2\"";
					// get new parents ...
					ret_par = HelperFunctions.getParentsInXML(uri_concept);					
					
// think of following cases:
// new node is located somewhere below the loaded level
// but this is only theoretically possible ... and should not occur in a new fresh system
					
// new node is located somewhere above the loaded level
// should be possible ?? yes, as not a direct parent then...					
					
				}else{
					// normal case ... UPDATE
					try{
					con = AbstractDataConnector.getConnection();	
					ClassMapper mapper = new ClassMapper();
					ArrayList<URI> oldparent_subclasses = controller.elementMapper.ClassMapper.selectAllClassesHavingClassInSubClassOf(uri_oParent);
					ArrayList<URI> newparent_subclasses = controller.elementMapper.ClassMapper.selectAllClassesHavingClassInSubClassOf(uri_nParent);
					if (newparent_subclasses == null)
						newparent_subclasses = new ArrayList<URI>();
					if (oldparent_subclasses != null)
						oldparent_subclasses.remove(uri_concept);
					newparent_subclasses.add(uri_concept);
					if (!uri_oParent.getLocalName().equals("")){
						mapper.updateAllClassesHavingClassInSubClassOf( con,uri_oParent, oldparent_subclasses, Mapper.selectHasVersionDateTimeString(uri_oParent) );
					}
					if(	mapper.exceptionsOccured()==false ) {
						if (!uri_nParent.getLocalName().equals("")){
							mapper.updateAllClassesHavingClassInSubClassOf( con,uri_nParent, newparent_subclasses, Mapper.selectHasVersionDateTimeString(uri_nParent) );
						}
						if(	mapper.exceptionsOccured()==false ) {
							con.commit();
							ret_ok = "\"yes\"";
						}else{
							con.rollback();
							ret_ok = "\"err3\"";
						}
					}else{
						con.rollback();
						ret_ok = "\"err3\"";
					}

					}catch( Exception e ) {
						con.rollback();
						ret_ok = "\"err3\"";
					}
					finally {
						con.close();
					}
				}		
		}
		catch(Exception e){System.out.println(e.toString());}
		String ret = "<dndupdateresponse ok="+ret_ok+">";
		if(!ret_par.equals("")){
			ret += ret_par;
		}
		ret+="</dndupdateresponse>";
		//ret = "<![CDATA[" + form + "]]>";
		
		// --------------------------

		//ret = "<handleupdateresponse><" + cssidcontent + ">" + ret + "</" + cssidcontent + "></handleupdateresponse>";
		
	    PrintWriter out = response.getWriter();
		
	    //out.println("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
	    
	    out.println( ret );
	}  	  	  	    
}
